import {
  ds
} from "../../../../tools/data"
import {
  ui
} from "../../../../tools/ui"
import {
  checkTool
} from "../../../../tools/check"
import {
  pages
} from "../../../../tools/pages"
Page({
  data: {
    action: 'new',
    mod: {},
    bgImg: '',
    id: '', // from options
  },
  async init() {
    const that = this,
      _ = ds.cmd
    ds.coll('module')
      .where({
        _id: _.eq(this.data.id)
      })
      .get({
        success: function (res) {
          const mod = res.data[0]
          that.setData({
            mod
          })
          that.loadBgImg(mod.img)
        }
      });
  },
  backTap() {
    pages.back()
  },
  saveTap(e) {
    ui.loading()
    const {
      mod
    } = this.data
    // console.log(mod)
    ds.cloudUpdate('module', mod._id, mod, res => {
      ui.loading(false)
      const success = res.result.errMsg.endsWith(":ok")
      ui.toast(success)
      if (success) pages.back()
    })
  },
  editSwiper(e) {
    const index = ui.eventData(e, 'index')
    const {
      mod
    } = this.data
    wx.navigateTo({
      url: `/pages/usercenter/module/slide/index?item=${JSON.stringify(mod)}`,
    })
  },
  setSlide(item, note) {
    this.setData({
      mod: item
    })
    this.loadBgImg(item.img)
  },
  loadBgImg(fileID) {
    const {
      mod
    } = this.data, that = this
    fileID && ui.getCloudFileUrl(fileID, url => {
      mod.bgImg = url
      that.setData({
        mod
      })
    })
  },
  changePos(e) {
    ui.loading();
    const name = ui.eventData(e, 'name')
    const {
      id,
      mod
    } = this.data

    checkTool.check([{
      title: "位置",
      regex: checkTool.CommonRegex.integer,
      value: mod[name]
    }])
    ds.cloudUpdate('module', id, {
      [`${name}`]: parseInt(mod[name])
    }, res => {
      ui.loading(false)
      const success = res.result.errMsg.endsWith(":ok")
      if (success) pages.back(prePage => {
        prePage.init()
      })
    })
  },
  onChangeInput(e) {
    const {
      mod
    } = this.data
    const name = ui.eventData(e, 'name'),
      index = ui.eventData(e, 'index')
    if (index) {
      mod.items[index].text = e.detail.value
      this.setData({
        mod
      })
    } else
      this.setData({
        [`mod.${name}`]: e.detail.value
      })
  },
  modColumnTap(e) {

  },
  changeNum(e) {
    const num = parseInt(e.detail.value)
    const {
      mod
    } = this.data
    if (num < mod.items.length) {
      ui.confirmx("是否删除末尾栏目？").then(res => {
        if (!res) return
        mod.items.pop()
        this.setData({
          mod
        })
      })
      return
    }
    mod.items.push({});
    this.setData({
      mod
    })
  },
  onLoad(option) {
    this.setData({
      id: option.id,
      action: option.action ?? 'new'
    });
    this.init();
  },
});